package com.gonsin.gview.common.utils;

import com.gonsin.base.GPageRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageableUtils {

    /**
     * 将pagepo转换为JPA 的pageable
     * @param pagePo
     * @return
     */
    public static Pageable toPageable(GPageRequest pagePo) {
        return toPageableMyBatis(pagePo);
    }

    /**
     * 将pagepo转换为JPA 的pageable
     * @param pagePo
     * @return
     */
    public static Pageable toPageableMyBatis(GPageRequest pagePo){
        if(pagePo == null){
            return PageRequest.of(0, Integer.MAX_VALUE);
        }
        Sort sort = null;
        if(StringUtils.isNotEmpty(pagePo.getSort())){
            String[] sortItems = pagePo.getSort().split(",");
            for (String item : sortItems) {
                if (!item.startsWith("+") && !item.startsWith("-")) {
                    continue;
                }
                Sort.Direction sortDirection;
                if(item.startsWith("+")){
                    sortDirection = Sort.Direction.ASC;
                    item = item.replace("+","");
                }else{
                    sortDirection = Sort.Direction.DESC;
                    item = item.replace("-","");
                }
                if (sort == null) {
                    sort = Sort.by(sortDirection, humpToLine(item));
                } else {
                    sort = sort.and(Sort.by(sortDirection, humpToLine(item)));
                }
            }
        }
        if(sort == null){
            sort = Sort.unsorted();
        }
        return PageRequest.of(pagePo.getPage(), pagePo.getCount(), sort);
    }

    /**
     * 转换驼峰命名
     */
    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    private static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString().toUpperCase();
    }

}
